package org.sg20.wordcooccurrence;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;

public class WordCooccurrenceReducer extends Reducer<Text, Text, Text, Text> {
    @Override
    protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
        ArrayList<String> list = new ArrayList<>();
        for (Text value : values) {
            list.add(value.toString());
        }
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = i + 1; j < list.size(); j++) {
                if (!list.get(i).equals(list.get(j))) { // <monkey, monkey> is not permitted.
                    context.write(new Text("<" + list.get(i) + "," + list.get(j) + ">"), new Text("1"));
                    context.write(new Text("<" + list.get(j) + "," + list.get(i) + ">"), new Text("1"));
                }
            }
        }
    }
}
